package com.example.inventory

import androidx.lifecycle.*
import com.example.inventory.data.Item
import com.example.inventory.data.ItemDao
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class InventoryViewModel(private val itemDao: ItemDao): ViewModel() {

    val allItems: LiveData<List<Item>> = itemDao.getItems().asLiveData()

    suspend fun addItem(name: String, price: String, count: String) = withContext(Dispatchers.IO) {
        val item = Item(itemName = name, itemPrice = price.toDouble(), quantityInStock = count.toInt())
        itemDao.insert(item)
    }

    fun validate(name: String, price: String, count: String) =
        !(name.isBlank() || price.isBlank() || count.isBlank())

    fun retrieveItem(id: Int): LiveData<Item> {
        return itemDao.getItem(id).asLiveData()
    }

    private suspend fun updateItem(item: Item) = withContext(Dispatchers.IO) {
        itemDao.update(item)
    }

    suspend fun sellItem(item: Item) {
        if (isStockAvailable(item)) {
            // 类似 js 的 Object.assign
            val newItem = item.copy(quantityInStock = item.quantityInStock - 1)
            updateItem(newItem)
        }
    }

    fun isStockAvailable(item: Item) = item.quantityInStock > 0

    suspend fun deleteItem(item: Item) = withContext(Dispatchers.IO) {
        itemDao.delete(item)
    }

    suspend fun updateItem(id: Int, name: String, price: String, count: String) {
        val item = Item(
            id = id,
            itemName = name,
            itemPrice = price.toDouble(),
            quantityInStock = count.toInt()
        )
        updateItem(item)
    }
}

class InventoryViewModelFactory(private val itemDao: ItemDao): ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(InventoryViewModel::class.java)) {
            @Suppress("UNCHECKED_CAST")
            return InventoryViewModel(itemDao) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }

}